package com.orange.api;

import java.util.Collection;
import server.rest.ContentType;
import server.rest.HttpContext;
import server.rest.HttpMethod;
import server.rest.Rest;
import server.rest.SessionType;
import server.rest.sessions.Expiration;
import server.rest.sessions.SessionManagerController;

public class SessionHandler implements Expiration<String, Long, UserSession>
{

    SessionManagerController<String, Long, UserSession> controller;

    public SessionHandler()
    {
    }
    
    public SessionHandler(SessionManagerController<String, Long, UserSession> controller)
    {
        setController(controller);
    }

    public void expire(Collection<UserSession> sessions)
    {
        for (UserSession session : sessions)
        {
            System.out.println(String.format("key: %s \n created: %s \n  lastUpdated : %s", session.getKey(),
                session.getCreated(), session.getLastRefresh()));
        }
    }

    @Rest(method = HttpMethod.GET, schema = "/login/(userid)", internal = false)
    public void login(HttpContext context) throws Throwable
    {
        String userid = context.getParameter("userid");
        UserSession session = (UserSession) this.controller.getSession(userid);
        if (session != null)
        {
            context.sendHtml("Already logged in");
        }
        else
        {
            session = new UserSession(userid, Long.parseLong(userid));
            this.controller.add(session);
            context.sendHtml("Login OK. Key=" + userid);
        }
    }

    @Rest(method = HttpMethod.GET, schema = "/logout/(key)", sessionType = SessionType.SESSION, internal = false)
    public void logout(HttpContext context, UserSession session) throws Throwable
    {
        this.controller.remove(session);
        context.sendHtml("Logout. Key=" + session.getKey());
    }

    @Rest(method = HttpMethod.GET, schema = "/add/(key)/(value)", sessionType = SessionType.SESSION, internal = false)
    public void add(HttpContext context, UserSession session) throws Throwable
    {
        long value = Long.parseLong(context.getParameter("value"));
        context.sendHtml("Sum=" + session.getAttrubites().size());
        session.add("test", value);
        context.sendHtml("Sum=" + session.getAttrubites().size());
    }

    public void setController(SessionManagerController<String, Long, UserSession> controller)
    {
        this.controller = controller;
        this.controller.setExpiration(this);
    }
}
